package autokeyboard.data;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import javax.swing.JOptionPane;

/**
 * This class is used to read access file from soft
 * @author HoldTheHand
 *
 */
public class DataAccess {

	/**
	 * Read a file with your input path
	 * 
	 * @param path
	 * @return all document in your file
	 */
	public String readFile(InputStream in) {
		String text = "";
		try {
			String line;
			BufferedReader bf = new BufferedReader(new InputStreamReader(in));

			while ((line = bf.readLine()) != null) {
				text += line +"\n";
			}
			if(text.endsWith("\n"))
				text.substring(0, text.length() - 1);
			bf.close();
		} catch (Exception e) {
		}

		return text;
	}
	
	/**
	 * Read a file with your input path
	 * 
	 * @param path
	 * @return all document in your file
	 */
	public String readFile(String path) {
		String text = "";
		try {
			String line;
			BufferedReader bf = new BufferedReader(new FileReader(new File(path)));

			while ((line = bf.readLine()) != null) {
				text += line +"\n";
			}
			if(text.endsWith("\n"))
				text.substring(0, text.length() - 1);
			bf.close();
		} catch (Exception e) {
		}

		return text;
	}
	
	/**
	 * Read file with encode UTF-8 from your input path
	 * @param file
	 * @return
	 */
	public String readFileUTF8(InputStream in) {
		String text = "";
		Charset cs = Charset.forName("UTF-8");
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, cs))) {
			String line;

			while ((line = reader.readLine()) != null) {
				text += line + "\n";
			}
			reader.close();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null,
					"File not found. Please try another path", "Message", 0,
					null);
		}
		return text;
	}

	/**
	 * Write a file with your input path, and your text
	 * @param path
	 * @param text
	 */
	public void writeFile(String path, String text) {
		try {
			BufferedWriter bf = new BufferedWriter(new FileWriter(
					new File(path)));
			bf.write(text);
			bf.close();
		} catch (Exception e) {
		}
	}
}
